package com.thread;

public class ProduceConsumer {
	public static void main(String[] args) {
		Resource r = new Resource();
		Produce produce = new Produce(r);
		Consumer consumer = new Consumer(r);
		Thread t1 = new Thread(produce);
		Thread t11 = new Thread(produce);
		Thread t2 = new Thread(consumer);
		Thread t22 = new Thread(consumer);
		// 开启多个生产多个消费
		t1.start();
		t11.start();
		t2.start();
		t22.start();
	}
}

// 资源
class Resource {
	private String name;
	private int num = 1;
	private boolean flag = false;

	// 生产
	public synchronized void set(String name) {
		while (flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.name = name + num;
		num++;
		System.out.println(Thread.currentThread().getName() + "---生产者---" + this.name);
		flag = true;
		notifyAll();
	}

	// 消费
	public synchronized void get() {
		while (!flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() + "---消费者---" + this.name);
		flag = false;
		notifyAll();
	}
}

// 生产者
class Produce implements Runnable {
	private Resource r;

	public Produce(Resource r) {
		this.r = r;
	}

	public void run() {
		for (int i = 50; i < 200; i++) {
			r.set("面包"); // 开始生产
		}
	}
}

// 消费者
class Consumer implements Runnable {
	private Resource r;

	public Consumer(Resource r) {
		this.r = r;
	}

	public void run() {
		for (int i = 0; i < 200; i++) {
			r.get(); // 开始消费
		}
	}
}